package com.uphone.kingmall.adapter;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.uphone.kingmall.activity.SettleActivity;
import com.uphone.kingmall.bean.SettleCartBean;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import static com.uphone.kingmall.app.MyApplication.mContext;

/**
 * <pre>
 *     author : radish
 *     e-mail : 15703379121@163.com
 *     time   : 2019/3/20
 *     desc   :
 * </pre>
 */
public class SettleAdapter extends BaseAdapter {
    private final Activity mActivity;
    private OnShopItemClickListener listener;
    private List<EditText> editTextList = new ArrayList<>();
    int totalHeight = 0;
    int count = 0;
    List<SettleCartBean.ShopGoodsBean> dataList = new ArrayList<>();
    String[] remarkList;

    public SettleAdapter(Activity activity, OnShopItemClickListener listener) {
        this.mActivity = activity;
        this.listener = listener;
    }


    /**
     * 计算金币抵扣金额
     *
     * @param helper
     * @param item
     */
    private double loadScoreDeductFee(View helper, SettleCartBean.ShopGoodsBean item) {
        double realFee = 0;
        double scoreDeductFee = item.getScoreDeductFee();
        double sumGoodsFee = item.getSumGoodsFee();
        if (sumGoodsFee > scoreDeductFee) {
            realFee = scoreDeductFee;
        } else {
            CheckBox tvPostFee = helper.findViewById(R.id.cb_logitics);
            if (tvPostFee.isChecked()) {
                //快递
                double postFee = item.getPostFee();
                double sumPostFee = new BigDecimal(sumGoodsFee).add(new BigDecimal(postFee)).doubleValue();
                if (sumPostFee > scoreDeductFee) {
                    realFee = scoreDeductFee;
                } else {
                    realFee = sumPostFee;
                }
            } else {
                //到店
                realFee = sumGoodsFee;
            }
        }
        item.setScoreRealFee(realFee);
        setText(helper, R.id.tv_integral_price, String.format(Locale.CHINA, "¥%.2f", realFee));
        return realFee;
    }

    @Override
    public int getCount() {
        return dataList == null ? 0 : dataList.size();
    }

    @Override
    public Object getItem(int position) {
        return dataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LogUtils.e("posotion:" + position);
        final View view = View.inflate(mActivity, R.layout.kingmall_item_rv, null);
        final LinearLayout ll = view.findViewById(R.id.ll);
        final SettleCartBean.ShopGoodsBean item = dataList.get(position);
        if (position == 0) {
            totalHeight = 0;
            count = 0;
        }
        ll.post(new Runnable() {
            @Override
            public void run() {
                totalHeight += ll.getMeasuredHeight();
                count++;
                if (count == dataList.size() && mActivity != null && mActivity instanceof SettleActivity) {
                    ((SettleActivity) mActivity).setRecycle(totalHeight);
                }
            }
        });
        setText(view, R.id.tv_shop_name, item.getShopName() + "");
        RecyclerView rvGood = view.findViewById(R.id.rv_good);
        rvGood.setLayoutManager(new LinearLayoutManager(mContext));
        SettleGoodAdapter adapter = new SettleGoodAdapter();
        rvGood.setAdapter(adapter);
        adapter.setNewData(item.getGoods());
        TextView tv_home_price = view.findViewById(R.id.tv_home_price);
        CheckBox cb_home = view.findViewById(R.id.cb_home);
        LinearLayout linear_home = view.findViewById(R.id.linear_home);
        TextView tv_store_price = view.findViewById(R.id.tv_store_price);
        final CheckBox cb_store = view.findViewById(R.id.cb_store);
        TextView tv_logitics_price = view.findViewById(R.id.tv_logitics_price);
        final CheckBox cb_logitics = view.findViewById(R.id.cb_logitics);
        tv_logitics_price.setText("¥" + item.getPostFee());

        cb_store.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                cb_logitics.setChecked(!b);
                if (b) {
                    item.setPost(false);
                    item.setPostType(2);
                    dataList.set(position, item);
                    if (listener != null) {
                        listener.calculationPrice(position, item);
                    }
                }
            }
        });
        cb_logitics.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                cb_store.setChecked(!b);
                if (b) {
                    item.setPost(true);
                    item.setPostType(1);
                    dataList.set(position, item);
                    if (listener != null) {
                        listener.calculationPrice(position, item);
                    }
                }
            }
        });

        cb_home.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    item.setInstallationType(1);
                } else {
                    item.setInstallationType(0);
                }
                dataList.set(position, item);
                if (listener != null) {
                    listener.calculationPrice(position, item);
                }
            }
        });

        if (item.getInstallationFee() > 0) {
            linear_home.setVisibility(View.VISIBLE);
            tv_home_price.setText("￥" + item.getInstallationFee());
        } else {
            linear_home.setVisibility(View.GONE);
        }
//        final TextView tvPostFee = view.findViewById(R.id.tv_postFee);
        EditText etRemark = view.findViewById(R.id.et_remark);
//        etRemark.setFocusableInTouchMode(true);
//        etRemark.requestFocus();
        editTextList.add(etRemark);
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                remarkList[position] = editable.toString();
            }
        });
        etRemark.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.setFocusableInTouchMode(true);
                v.requestFocus();
                KeyboardUtils.showSoftInput(mActivity);
                return true;
            }
        });


        final CheckBox cbBalance = view.findViewById(R.id.cb_balance);
        final CheckBox cbIntegral = view.findViewById(R.id.cb_integral);

        setText(view, R.id.tv_balance_price, "¥" + item.getYueDeductFee());
        item.setScoreRealFee(loadScoreDeductFee(view, item));
        cbBalance.setChecked(false);
        cbIntegral.setChecked(false);
        cbBalance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbBalance.setChecked(!item.isYueFeeSelect());
                cbIntegral.setChecked(false);
                item.setYueFeeSelect(cbBalance.isChecked());
                item.setScoreFeeSelect(false);
                dataList.set(position, item);
                if (listener != null) {
                    listener.calculationPrice(position, item);
                }
            }
        });

        cbIntegral.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cbIntegral.setChecked(!item.isScoreFeeSelect());
                cbBalance.setChecked(false);
                item.setScoreFeeSelect(cbIntegral.isChecked());
                item.setYueFeeSelect(false);
                dataList.set(position, item);
                if (listener != null) {
                    listener.calculationPrice(position, item);
                }
            }
        });

//        if (item.isPost()) {
//            setText(view, R.id.tv_postFee, "快递：" + item.getPostFee() + "");
//        } else {
//            setText(view, R.id.tv_postFee, "到店");
//        }
//        // 选择消费方式
//        tvPostFee.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                View inflate = View.inflate(mActivity, R.layout.dialog_settle_way, null);
//                final PopupUtil popupFilter = PopupUtil.getInstance(mContext, inflate);
//                popupFilter.setBasisView(v).showDirection(PopupUtil.Direction.UNDER);
//                inflate.findViewById(R.id.tv_express).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        tvPostFee.setText("快递：" + item.getPostFee());
//                        popupFilter.dismiss();
//                    }
//                });
//                inflate.findViewById(R.id.tv_shop).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        tvPostFee.setText("到店");
//                        popupFilter.dismiss();
//                    }
//                });
//                popupFilter.setDismissListener(new PopupWindow.OnDismissListener() {
//                    @Override
//                    public void onDismiss() {
//                        if (popupFilter != null) {
//                            popupFilter.release();
//                        }
//                    }
//                });
//            }
//        });
        return view;
    }

    private void setText(View view, int resId, String text) {
        View viewById = view.findViewById(resId);
        if (viewById != null && viewById instanceof TextView) {
            ((TextView) viewById).setText(text);
        }
    }

    public interface OnShopItemClickListener {
        void calculationPrice(int position, SettleCartBean.ShopGoodsBean item);
    }

    public String[] getRemarkList() {
        return remarkList;
    }

    public void setList(List<SettleCartBean.ShopGoodsBean> dataList) {
        this.dataList = dataList;
        remarkList = new String[dataList.size()];
        notifyDataSetChanged();
    }
}
